--
-- Author: yawei.zhu
-- Date: 2018-12-13 15:27:41
--
-- TaskTrackRender
--
local IconRender = require("app.widget.renders.IconRender")

local ClassRef = app.mvc.createListViewCell(...)

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.TrackTaskItemNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)
    self:setContentSize(self._ui.Panel:getContentSize())

    self._iconRender = IconRender.create(self._ui.Base_icon)
    self._iconRender:setTipEnable(true)

    self._ui.Panel:setTouchEnabled(true)

    self._ui.Panel:addClickEventListener(function(sender)
        if not self._data or not  self._data.data  then
            return
        end
        local taskData = self._data.data 
        local taskC = taskData:getConfig()
        if not taskC then
            return
        end
        if self._onClick then
            executeFunc(self._onClick, "onTrackItem", taskC)
        else
            self:dispatchCellEvent("onTrackItem", taskC)
        end
    end)

    self:refresh()
end

function ClassRef:refresh()
    if not self._data then return end
    local taskData = self._data.data
    if not taskData then
        return 
    end
    self:refreshItem(taskData)
end

function ClassRef:enableTouch()
    if self._ui and cc.isAlive(self._ui.Panel) then
        self._ui.Panel:setTouchEnabled(true)
    end
end

function ClassRef:disableTouch()
    if self._ui and cc.isAlive(self._ui.Panel) then
        self._ui.Panel:setTouchEnabled(false)
    end
end

function ClassRef:refreshItem(task)
    local root = self._ui.Panel
    self:refreshTrackState()
    local taskTypeNode = self._ui["Panel/Text_type"]
    local taskNameNode = self._ui["Panel/Text_name"]
    local desNode = self._ui["Panel/Text"]
    local btnTrack = self._ui["Panel/button"]
    local iconNode = self._ui["Panel/icon"]
    local iconNodeMark = self._ui["Panel/icon01"]

    if iconNode.listener then
        self:getEventDispatcher():removeEventListener(iconNode.listener)
        iconNode.listener = nil
    end

    local taskC = task:getConfig()
    if not taskC then return end

    local progressStr = ""
    if task:getDefaultTotal() > 0 and tonumber(taskC.conditionShow) ~= 2 then
        progressStr = task:getDefaultDone() .. "/" .. task:getDefaultTotal()
    end
    
    local descStr = L(taskC.name)
    local subName = descStr
    if not task:isMain() then
        subName = string.usubstr(descStr, Constant.Task_Name_Limit_Count) -- 截取任务名字
        if string.ulen(descStr) > Constant.Task_Name_Limit_Count then
            subName = subName .. "..."
        end
    end    
    local tName = subName .. " " .. progressStr
    taskNameNode:setString(tName)

    local taskTypeName = ""
    if task:isMain() then
        taskTypeName = L("tasktracking_001")
    elseif task:isBounty() then
        taskTypeName = L("tasktracking_002")
    elseif task:isSide() then
        taskTypeName = L("tasktracking_003")
    elseif task:isDaily() then
        taskTypeName = L("tasktracking_004")
    end
    taskTypeNode:setString(taskTypeName)

    local gradeNode = root:getChildByName("bg01")
    gradeNode:loadTexture("ui_resources/main/main_renwu_cell.png", 1)
    task:setTaskIcon(iconNode, gradeNode, self._iconRender, iconNodeMark)

    btnTrack:setVisible(false)
  

    local taskTarget = L(taskC.target)

    -- 是否添加过Node（主要是为了减少打印错误日志）
    if self._alreadyAddNode then
        self._alreadyAddNode = false
        root:removeChildByName("temp_text_node")
    end

    local Wildcard = app:getClass("Wildcard")
    local wildcard = Wildcard.new()

    local scaleX = desNode:getScaleX()
    local scaleY = desNode:getScaleY()

    if not wildcard:isNeedParse(taskTarget) then
        desNode:setVisible(true)
        desNode:setString(taskTarget)
    else
        if desNode.getLabelEffectType and desNode.getOutlineSize and desNode.getEffectColor then
            desNode:setVisible(false)

            local eType = desNode:getLabelEffectType()
            if eType == 1 then
            end

            local outlineSize = desNode:getOutlineSize()
            local outlineColor = desNode:getEffectColor()
            local fontName = desNode:getFontName()
            local fontSize = desNode:getFontSize()
            local width = desNode:getContentSize().width - fontSize
            local height = desNode:getContentSize().height * scaleY

            local name = UD:getPlayer().name
            local jobStr = L(GD:queryClass(UD:getPlayer().classID).string)

            wildcard:setTextDefaultColor(display.COLOR4_WHITE)
            local wordsTab = wildcard:parseWildcardStrings(taskTarget,fontSize,jobStr,"sex",name)
            local textNode,tWidth,tHeight = wildcard:buildTextNode(wordsTab,width,fontName,outlineColor,outlineSize)
            root:addChild(textNode)
            textNode:setAnchorPoint(cc.p(0,0))
            textNode:setScaleX(scaleX)
            textNode:setScaleY(scaleY)
            textNode:setName("temp_text_node")

            self._alreadyAddNode = true

            local pos = cc.p(desNode:getPosition())
            pos.y = pos.y + height
            textNode:setPosition(pos)
        else
            desNode:setString(taskTarget)
        end
    end


    -- 主线任务设置下划线
    if self._textRT ~= nil then
        self._textRT:removeFromParent()
        self._textRT = nil
    end

    
   local defaults = {}
   -- defaults["KEY_WRAP_MODE"] = 1
   defaults["KEY_FONT_FACE"] = Res.font
   defaults["KEY_FONT_SIZE"] = desNode:getFontSize()
   defaults["KEY_VERTICAL_SPACE"] = 3
   
   local str = string.format("<u>%s</u>", taskTarget)
   local richText = ccui.RichText:createWithXML(str, defaults)
   if nil == richText then
   else
       desNode:setString("")
       if self._alreadyAddNode then
           self._alreadyAddNode = false
           root:removeChildByName("temp_text_node")
       end
   
       richText:setAnchorPoint(cc.p(0, 0.5))
       richText:setPosition(desNode:getPosition())
       richText:ignoreContentAdaptWithSize(false)
       self._ui.Panel:addChild(richText)
       self._textRT = richText
      
       richText:setContentSize(cc.size(desNode:getContentSize().width, 0))
       richText:formatText()
       local t_size = richText:getFormatSize()
       richText:setContentSize(t_size)
   
       richText:setScaleX(scaleX)
       richText:setScaleY(scaleY)
   end
end

function ClassRef:setSelectBG(visible)
    -- self._ui.ontrack_bg:setVisible(visible)
    if visible then
        if not self._markNode then
            local mark = cc.CSLoader:createNode(Res.TrackTaskItemBgNode)
            self._ui.bg:addChild(mark)
            self._markNode = mark
        end
        self._markNode:setVisible(true)
        local timeline = self._markNode:getTimeline()
        timeline:gotoFrameAndPlay(0, true)
    else
        if self._markNode then
            self._markNode:setVisible(false)
            local timeline = self._markNode:getTimeline()
            timeline:gotoFrameAndPause(0)
        end
    end
end

function ClassRef:onBtnClick(cb)
    self._onClick = cb
end


function ClassRef:onCellsShareDataChange(shareData)
    self:refreshTrackState()
end


function ClassRef:refreshTrackState()
    if not self._cellModel then
        return
    end
    local shareData = self._cellModel:getShareData()
    local trackTaskId
    if shareData then
        trackTaskId = shareData.trackTaskId
    end
    local isSelect = false
    if self._data or self._data.data  then
        local taskData = self._data.data 
        local id = taskData:getId()
        isSelect = trackTaskId == id
    end
    if isSelect then
        self:setSelectBG(true)
    else
        self:setSelectBG(false)
    end
end


return ClassRef
